home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 575 < prev    next >
Internet Message Format  |  1996-08-06  |  2KB

  1. Path: solon.com!not-for-mail
  2. From: danpop@mail.cern.ch (Dan Pop)
  3. Newsgroups: comp.lang.c.moderated,comp.std.c
  4. Subject: Re: 'h' modifier in printf
  5. Date: 14 Mar 1996 21:14:01 -0600
  6. Organization: CERN European Lab for Particle Physics
  7. Sender: clc@solutions.solon.com
  8. Approved: clc@solutions.solon.com
  9. Message-ID: <4ian9p$h5t@solutions.solon.com>
  10. References: <4i801c$455@solutions.solon.com>
  11. NNTP-Posting-Host: solutions.solon.com
  12. X-Newsreader: NN version 6.5.0 #7 (NOV)
  13.  
  14. In <4i801c$455@solutions.solon.com> tada@athena.mit.edu (Michael J Zehr) writes:
  15.  
  16. >The "h" modifier says the corresponding argument will be printed as a
  17. >short or unsigned short.
  18. >
  19. >So, given:
  20. >
  21. >short s;
  22. >printf("%d", s);
  23. >printf("%hd", s);
  24. >
  25. >(Assuming of course that s has been initialized at some point.)
  26. >
  27. >Can these two ever be different?
  28.  
  29. No.
  30.  
  31. >This is the main question I'm interested, but as a followup, if these
  32. >always result in the same output, why is the 'h' modifier defined in the
  33. >first place?
  34.  
  35. Because there are other examples where the output is actually changed by
  36. the 'h' modifier:
  37.  
  38. int i = SHRT_MAX + 1;  /* assuming that INT_MAX > SHRT_MAX */
  39. short s = -1;
  40.  
  41. printf("%d", i);
  42. printf("%hd", i);
  43.  
  44. printf("%x", (unsigned)s);
  45. printf("%hx", (unsigned)s);
  46.  
  47. >Some speculations:
  48. >
  49. >int i;
  50. >printf("%hd", i);
  51. >printf("%d", (short)i);
  52. >
  53. >This question is stretching a bit to try to find what if anything the
  54. >'h' modifier is ever used for.  Certainly the first line would have a
  55. >different result without the 'h', but casting seems like it ought to
  56. >have the same result.
  57.  
  58. You have just discovered that there's more than one way to achieve the
  59. same result in C :-)  The second method involves two conversions, while
  60. the first one needs only one (inside printf).
  61.  
  62. Dan
  63. --
  64. Dan Pop
  65. CERN, CN Division
  66. Email: danpop@mail.cern.ch 
  67. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  68.